/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.app.controller;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yanlight.exception.ErrorType;
import com.yanlight.support.http.Response;
import com.yanlight.util.ResponseUtil;

/**
 * 
 *
 * @author haolw
 * @time 2017/06/27
 */
@Controller
public class RouterController {
	private final String VIEW_PREFIX = "WEB-INF/views";
	private final String VIEW_SUFFIX = ".html";
	private final String VIEW_404 = "404";

	@GetMapping("/**")
	public String route(HttpServletRequest request, HttpServletResponse response) {
		String view = request.getServletPath();
		if (!existsView(request, view)) {
			view = VIEW_404;
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
		return view;
	}

	@ResponseBody
	@PostMapping("/**")
	public Response routePost(HttpServletRequest request) {
		ErrorType error = ErrorType.NO_SERVICE;
		Integer errorCode = error.getCode();
		String errorMsg = error.getZhCnMsg();
		return ResponseUtil.fail(errorCode, errorMsg);
	}

	@GetMapping("/error/404")
	public String process404(HttpServletRequest request, HttpServletResponse response) {
		return "404";
	}

	@GetMapping("/error/500")
	public String process500(HttpServletRequest request, HttpServletResponse response) {
		return "500";
	}
	
	private boolean existsView(HttpServletRequest request, String name) {
		String rootPath = getRootPath(request);
		name = name.concat(VIEW_SUFFIX);
		File view = new File(rootPath, name);
		return view.exists();
	}

	private String getRootPath(HttpServletRequest request) {
		String realPath = request.getServletContext().getRealPath(VIEW_PREFIX);
		return StringUtils.cleanPath(realPath);
	}

}
